'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 结束战斗
 * @author agl
 */

var async = require('async');
var moment = require('moment');
var Code = require('../../../../consts/code');
var moduleType = require('../../../../consts/moduleType');
var operationType = require('../../../../consts/operationType');
var atkData = require('../../../../libs/war/atkData');
var unionBossData = require('../../../../libs/war/unionBossData');
var constantUtil = require('../../../../util/constantUtil');
var PlayerManager = require('../../../../libs/playerManager');
var taskService = require('../../../../services/taskService.js');
var rewardService = require('../../../../services/rewardService.js');
var unionBossService = require('../../../../services/unionBossService.js');
var unionGroupModel = require('../../../../models/unionGroupModel.js');
var unionBossModel = require('../../../../models/unionBossModel.js');
var unionBossConf = require('../../../../config/unionBossConf.js');

/**
 * 结束战斗
 */
module.exports = function (msg, session, next) {
    var role_id = session.uid;
    var damage = msg.damage;

    var atk_data;
    var def_data;

    var union_group_model;
    var union_boss_model;
    var union_id;
    var reward_list = [];

    if (!damage) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var callNext = function (err, res) {
        if (!union_id) {
            return next(err);
        }

        unionBossModel.unLockBoss(union_id, function (err1) {
            if (!!err1) {
                console.error(err1);
                return next(err1);
            }
            return next(err, res);
        });
    };

    damage = Math.ceil(damage);

    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(['role', 'role_union_boss', 'task', 'build', 'soldier', 'daily_task', 'achieve', 'sevenDayActivity', 'accrued'], cb);
            },
            function (cb) {
                union_id = player_manager.role.union_id;
                if (union_id === 0) {
                    return next(null, {
                        code: Code.UNION_IS_NOT_JOIN
                    });
                }

                // 联盟信息
                unionGroupModel.getById(union_id, cb);
            },
            function (model, cb) {
                union_group_model = model;

                // 联盟BOSS
                unionBossModel.findById(union_id, cb);
            },
            /* jshint maxstatements:100 */
            function (model, cb) {
                union_boss_model = model;
                if (union_boss_model.lock_role_id !== role_id) {
                    return next(null, {
                        code: Code.UNIOIN_BOSS_NO_IN_BATTLE
                    });
                }

                var now_tm = moment().unix();
                if (union_boss_model.lock_end_tm < now_tm) {
                    return next(null, {
                        code: Code.UNIOIN_BOSS_BATTLE_TIMEOUT
                    });
                }

                // ----------以下需解锁-------------------------------
                var boss_id = union_boss_model.curr_boss_id;
                var boss_hp = union_boss_model.curr_boss_hp;
                if (boss_hp < 1) {
                    return callNext(null, {
                        code: Code.UNIOIN_BOSS_ALREADY_DIED
                    });
                }
                if (damage > boss_hp) {
                    damage = boss_hp;
                }

                if (damage > 0) {
                    // 保存BOSS伤害值(当前BOSS血量，伤害排行榜)
                    union_boss_model.setDamage(role_id, damage);

                    // 玩家累计伤害值
                    var role_union_boss_model = player_manager.role_union_boss;
                    role_union_boss_model.addTotalDamage(damage);
                }

                if (damage > 0 && union_boss_model.curr_boss_hp <= 0) {
                    console.log('--------击杀BOSS---------------');
                    // 发送最后击杀BOSS奖励
                    reward_list = unionBossConf.getLastKillReward(boss_id);
                    var module_type = moduleType.MDL_UNION_BOSS;
                    var operation_type = operationType.OPR_UNION_BOSS_LAST_KILL_REWARD;
                    var res_int_val = boss_id;
                    rewardService.addRewardListToRole(player_manager, reward_list, module_type, operation_type, res_int_val);

                    // 发放伤害排名奖励
                    unionBossService.doDamageRankReward(union_boss_model, function (err) {
                        cb(err, true);
                    });
                } else {
                    cb(null, false);
                }
            },
            function (killed_boss, cb) {
                if (killed_boss) {
                    // 保存到击杀列表中
                    var role_model = player_manager.role;
                    var role_name = role_model.name;
                    union_boss_model.appendToKilledBossList(role_id, role_name);

                    // 切换到下一个BOSS
                    _switchToNextBoss(union_boss_model);
                }

                union_boss_model.save(function (err) {
                    cb(err);
                });
            },
            function (cb) {
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return callNext(null, {
                    code: Code.FAIL
                });
            }
            return callNext(null, {
                code: Code.OK,
                result: {
                    boss_damage: damage,
                    reward_list: reward_list
                }
            });
        }
    );
};

// 切换到下一个BOSS
var _switchToNextBoss = function (union_boss_model) {
    var boss_id = union_boss_model.curr_boss_id;
    var bossConf = unionBossConf.getNextBossConf(boss_id);
    if (!bossConf) {
        // 当前是最后一个BOSS，则不切换
        return;
    }

    union_boss_model.damage_list = [];
    union_boss_model.lock_role_id = 0;
    union_boss_model.lock_end_tm = 0;
    union_boss_model.curr_boss_id = bossConf.id;
    union_boss_model.curr_boss_hp = bossConf.hp;
};
